package com.second.sixoo;

import java.io.ByteArrayOutputStream;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.zip.GZIPOutputStream;

public class FileUtils {
    static int length = Integer.MAX_VALUE; // 4g

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        // 为了以可读可写的方式打开文件，这里使用RandomAccessFile来创建文件。
        FileChannel fc = new RandomAccessFile("test.dat", "rw").getChannel();
        //注意，文件通道的可读可写要建立在文件流本身可读写的基础之上
        MappedByteBuffer out = fc.map(FileChannel.MapMode.READ_WRITE, 0, length);
        //写128M的内容
        for (int i = 0; i < length/4; i++) {
//            out.put((byte) 'x');
            out.putFloat(1.3f);
        }
        System.out.println("Finished writing");
        //读取文件中间6个字节内容
        System.out.println(System.currentTimeMillis()-start);
        fc.close();
    }

    public static byte[] gZip(byte[] data) {
        byte[] b = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(bos);
            gzip.write(data);
            gzip.finish();
            gzip.close();
            b = bos.toByteArray();
            bos.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return b;
    }
}
